<?php
/**
 * Created by PhpStorm.
 * User: yadongw
 * Date: 15-5-26
 * Time: 下午2:22
 */

namespace UcxApiSdk\Resource;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Message\Response;
use UcxApiSdk\Exceptions\UcxException;

class BaseResource
{
	static $url;
	static $baseApiUrl = "https://xapi.foxitcloud.com";
	/** @var  Client */
	public $client;
	static $access_token;

	public function apiUrl ($path = '', $pathArgs = [])
	{
		$url = static::$baseApiUrl.static::$url;
		if ($path) {
			$url .= '/'.$path;
		}
		if (self::$access_token) {
			$pathArgs['access-token'] = self::$access_token;
		}
		if (!empty($pathArgs)) {
			$url .= '?'.http_build_query($pathArgs);
		}

		return $url;
	}

	public function __construct ()
	{
		$this->client = new Client();
		$this->client->setDefaultOption('verify', false);
	}

	/**
	 * @param Response $response
	 * @return mixed
	 * @throws UcxException
	 */
	protected function handleResponse ($response)
	{
		if ($response->getStatusCode() == 200) {
			$data = $response->getBody();
			$data = json_decode($data, true);
		} else {
			$data = $response->getBody();
			$data = json_decode($data, true);
			throw new UcxException($data['message'], $data['code']);
		}

		return $data;
	}

	public function create ($data)
	{
		try {
			$response = $this->client->post($this->apiUrl(), ['json' => $data]);
		} catch (ServerException $e) {
			$response = $e->getResponse();
		}

		return $this->handleResponse($response);
	}

	public function update ($id, $data)
	{
		try {
			$response = $this->client->put($this->apiUrl($id), ['json' => $data]);
		} catch (ServerException $e) {
			$response = $e->getResponse();
		}

		return $this->handleResponse($response);
	}

	public function delete ($id)
	{
		try {
			$response = $this->client->delete($this->apiUrl($id));
		} catch (ServerException $e) {
			$response = $e->getResponse();
		}

		return $this->handleResponse($response);
	}

	public function find ($id = NULL, $expand = '')
	{
		try {
			$response = $this->client->get($this->apiUrl($id, ['expand' => $expand]));
		} catch (ServerException $e) {
			$response = $e->getResponse();
		}

		return $this->handleResponse($response);
	}

	public function findAll ($page = 1, $expand = '')
	{
		try {
			$response = $this->client->get($this->apiUrl('', ['page' => $page, 'expand' => $expand]));
		} catch (ServerException $e) {
			$response = $e->getResponse();
		}

		return $this->handleResponse($response);
	}

}